package com.fs.uc.nacos;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 崔超
 * 2021/12/11
 */
public class HttpUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
    public final static int CONNECTION_TIMEOUT = 5;
    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    //最大空闲线程数
    public final static int MAX_IDLE_CONNECTIONS = 10;
    //OkHTTP线程池空闲线程存活时间
    public final static long KEEP_ALIVE_DURATION = 30L;


    /**
     * client
     * 配置重试
     */
    private final static OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
            .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES))
            .build();


    /**
     * get请求，无需转换对象
     *
     * @param url     链接
     * @param headers 请求头
     * @return 响应信息
     */
    public static String get(String url, Map<String, String> headers) {
        try {
            Request.Builder builder = new Request.Builder();
            buildHeader(builder, headers);
            Request request = builder.url(url).build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            ResponseBody body = response.body();
            if (response.isSuccessful() && Objects.nonNull(body)) {
                String result = body.string();
                LOGGER.info("执行get请求, url: {} 成功，返回数据: {}", url, result);
                body.close();
                return result;
            }
        } catch (Exception e) {
            LOGGER.error("执行get请求，url: {} error：{}", url, e);
        }
        return null;
    }


    /**
     * 简单post请求
     *
     * @param url     请求url
     * @param headers 请求头
     * @param json    请求参数
     */
    public static String post(String url, Map<String, String> headers, String json) {
        try {
            RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
            Request.Builder builder = new Request.Builder();
            buildHeader(builder, headers);
            Request request = builder.url(url).post(body).build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            ResponseBody responseBody = response.body();
            if (response.isSuccessful() && Objects.nonNull(responseBody)) {
                String result = responseBody.string();
                LOGGER.info("执行get请求, url: {} 成功，返回数据: {}", url, result);
                responseBody.close();
                return result;
            }
        } catch (Exception e) {
            LOGGER.error("执行post请求，url: {},参数: {} 失败!", url, json, e);
        }
        return null;
    }


    /**
     * 设置请求头
     *
     * @param builder .
     * @param headers 请求头
     */
    private static void buildHeader(Request.Builder builder, Map<String, String> headers) {
        if (Objects.nonNull(headers) && headers.size() > 0) {
            headers.forEach((k, v) -> {
                if (Objects.nonNull(k) && Objects.nonNull(v)) {
                    builder.addHeader(k, v);
                }
            });
        }
    }

}
